﻿using BaseData.API.Read.Applications.HospitalInformation.Command;
using BaseData.Domain.HospitalInformation;
using BaseData.ErrorCode;
using BaseData.Infrastructure.Interfaces;
using BaseData.Infrastructure.Menu;
using MediatR;
using Microsoft.EntityFrameworkCore;

namespace BaseData.API.Read.Applications.HospitalInformation.CommandHandler
{
    /// <summary>
    /// 科室级联查询--命令
    /// </summary>
    public class DepartmentsMeunCommandHandler : IRequestHandler<DepartmentsMeunCommand, ApiResult<List<MenuItem>>>
    {
        private readonly IBaseRepository<Departments> departmentsRep;

        public DepartmentsMeunCommandHandler(IBaseRepository<Departments> departmentsRep)
        {
            this.departmentsRep = departmentsRep;
        }
        public async Task<ApiResult<List<MenuItem>>> Handle(DepartmentsMeunCommand request, CancellationToken cancellationToken)
        {
            var list = await GetDepartmentsById(0);
            return new ApiResult<List<MenuItem>>
            {
                Code = ApiEnum.查询成功,
                Message = ApiEnum.查询成功.ToString(),
                Data =list
            };
        }
        /// <summary>
        /// 返回父级对应的子集
        /// </summary>
        public async Task<List<MenuItem>> GetDepartmentsById(int ParentId)
        {
            try
            {
                var list = await departmentsRep.GetAll().Where(x => !x.Isdelete && x.parentId == ParentId).ToListAsync();
                List<MenuItem> menuItems= new List<MenuItem>();
                foreach (var item in list) 
                {
                    menuItems.Add(new MenuItem
                    {
                        value=item.DepartmentId,
                        label=item.DepartmentName,
                        children=await GetDepartmentsById(item.DepartmentId)
                    });
                    
                }
                return menuItems;
            }
            catch (Exception)
            {

                throw;
            }
        }
    }
}
